//
//  AppDelegate.m
//  Frame
//
//  Created by shiqing guo on 2018/12/7.
//  Copyright © 2018年 云数动能. All rights reserved.
//

#import "AppDelegate.h"

#import <CocoaLumberjack.h>
#import "MainTBC.h"
// ios10新的通知框架
#import <UserNotifications/UserNotifications.h>
#import "LoginVC.h"
#import "Macro.h"
#import "LaunchPagesVC.h"
#import "StringUtil.h"
#import "BaseJSONService.h"
#import "BaseNavigationController.h"
#import "MobileInputVC.h"
#import "AccountSysVM.h"
#import "FileManager.h"

#import <UMShare/UMShare.h>
#import <UMAnalytics/MobClick.h>
#import <UMCCommon/UMCommon/UMConfigure.h>
#import <WXApi.h>

#import "CommonHelper.h"
#import <CoreLocation/CoreLocation.h>
#import "NotificationHelp.h"
//#import "AutoUpdater.h"
#import "UserSettings.h"

@interface AppDelegate ()<WXApiDelegate>
// 当收到通知后，APP的状态
@property (nonatomic, assign) UIApplicationState appState;
@property (nonatomic, strong) MainTBC *mainTBC;
@property (nonatomic, strong) LoginVC *loginVC;

@property (nonatomic, strong) NSString *teamName;
@property (nonatomic, strong) NSString *teamToken;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 设置全局的Tabbar不透明
    if (IOS12) {
        [[UITabBar appearance] setTranslucent:NO];
    }
    
    // 处理UITableview上下偏移的问题
    [self setUPAdapteriOS11];
    
    // 设置推送服务
    [self registerAPNs];
    
    // 日志系统初始化
    [self initLogger];
    
    // 添加跳转到主页面/登录页面等通知
    [self addAccountNotification];
    
    // 当前沙盒路径
    NSLog(@"当前用户路径：%@", [FM baseCachePath]);
    
    // 启动全局网络监控: 检查全局参数
    [BaseJSONService netWorkReachability];
    
    // 设置导航栏全局样式
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.tag = 9999;
    
    // 服务端口url
    UserSaveInfo.serverUrl = @"https://testdnapp.bitkinetic.com";
    UserSaveInfo.msgCenterUrl = @"wss://testws.bitkinetic.com";

    // h5的url
    UserSaveInfo.h5Url = @"https://h5.bitkinetic.com";
    
    [self loadLaunch];
    
    return YES;
}

- (void)configUMSetting
{
}

- (void)confitUShareSettings
{
}

- (void)configUSharePlatforms
{

}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    // 发出转后台通知，让其他页面监听keyboardshow时特殊处理一下
    [NotificationHelp postNotification:NotificationDidEnterBackground object:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    // 后台转前台，非启动
    [NotificationHelp postNotification:NotificationWillEnterForeground object:nil];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
//    // 版本检查
//    [[AutoUpdater sharedInstance] checkUpdate];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

////////////////////////////// 通知推送的代理方法 //////////////////////////
#pragma mark - 通知推送
//远程推送通知
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 向APNS注册成功，收到返回的deviceToken
    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    NSString *dt = [token stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *dn = [dt stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *apnsToken = [dn stringByReplacingOccurrencesOfString:@" " withString:@""];
    [CommonHelper shared].deviceToken = apnsToken;
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    // 向APNS注册失败，返回错误信息error
    NSString *errorStr = [NSString stringWithFormat: @"%@", error];
    NSLog(@"errorStr = %@", errorStr);
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    [self handleNotification:notification.userInfo];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler {
    
    self.appState = application.applicationState;
    if (self.appState == UIApplicationStateActive) {   //当前是激活状态不处理
        return;
    }
    
    //如果是后台运行状态，跳转到之前的页面
    if (self.appState == UIApplicationStateBackground) {
        return;
    }
    
    // 处理点击横幅后的响应 userInfo
    [self handleNotification:userInfo];
    
}

#pragma mark - 点击横幅
//处理推送：
- (void)handleNotification:(NSDictionary *)userInfo {
    

}


////////////////////////////// Private fundation //////////////////////////
// 设置推送服务
- (void)registerAPNs
{
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    // iOS10 新的通知框架
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert;
    [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
        
    }];
}

#pragma mark - 日志系统初始化
- (void)initLogger
{
    //    // Enable XcodeColors
    //    setenv("XcodeColors", "YES", 0);
    //
    //    // 日志文件默认大小为1M，最多存储10个
    //    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    //    fileLogger.rollingFrequency = 60 * 60 * 24 * 7; // 24 hour rolling
    //    fileLogger.logFileManager.maximumNumberOfLogFiles = 10;
    //
    //    [DDLog addLogger:fileLogger];
    //
    //    //日志
    //    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    //    // And then enable colors
    //    [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
    //
    //    //测试
    //    DDLogError(@"Paper jam"); // 红色
    //    DDLogWarn(@"Toner is low"); // 橙色
    //    IOALog(@"Warming up printer (pre-customization)"); // 默认是黑色
}

#pragma mark - 跳转到主页面
- (void)go2MainTBC
{
    // 先销毁再创建
    [self destroyMainTBC];
    
    MainTBC *mainVC = [[MainTBC alloc] initWithIndex:self.nowIndex];
    self.window.rootViewController = mainVC;
    self.mainTBC = mainVC;
}

- (void)destroyMainTBC
{
    if (_mainTBC) {
        _mainTBC = nil;
        for (NSInteger index = 0; self.window.subviews.count; index ++) {
            UIView *view = self.window.subviews[0];
            [view removeFromSuperview];
            view = nil;
        }
    }
}

#pragma mark - 跳转到登录页面
- (void)go2LoginVC:(NSString *)message
{
    // 销毁 mainTBC
    [self destroyMainTBC];
    // 销毁 loginVC
    [self destroyLoginVC];
    // 清除token等上次登录的缓存
    [UserSaveInfo clearCache];
    [CommonHelper shared].team = nil;
    // 清除自动登录状态
    TheAppDel.wasAutoLogin = NO;
    // 重建登录页
    self.loginVC = [[LoginVC alloc] init];
    self.loginVC.strMessage = message;
    self.loginVC.baseVM = [[AccountSysVM alloc] init];
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:self.loginVC];
    self.window.rootViewController = nav;
}

- (void)destroyLoginVC
{
    if (_loginVC) {
        _loginVC = nil;
    }
}

#pragma mark - 加载引导页
- (void)loadLaunch
{
    NSArray *images = @[@"iPhone5.5_guide_1", @"iPhone5.5_guide_2", @"iPhone5.5_guide_3", @"iPhone5.5_guide_4"];
    BOOL isShowed = [LaunchPagesVC isShowed];
    //    isShowed = YES;
    if (isShowed) {
        
        LaunchPagesVC *launchVC = [[LaunchPagesVC alloc] init];
        self.window.rootViewController = launchVC;
        [launchVC launchPageControllerWithImages:images];
        
        WEAKSELF
        launchVC.loginBlock = ^{
            [weakSelf startFunctionPaga];
        };
        launchVC.registerBlock = ^{
            // 点击注册
            [weakSelf clickRegister];
        };
    }
    else
    {
        [self startFunctionPaga];
    }
    [self.window makeKeyAndVisible];
}

// 点击登录
- (void)startFunctionPaga
{
    if (!UserSaveInfo.token || 0 == UserSaveInfo.token.length) {
        [self go2LoginVC:nil];
    }
    else
    {
        self.wasAutoLogin = YES;
        [self go2MainTBC];
    }
}

// 点击新用户注册
- (void)clickRegister
{
    MobileInputVC *mbInputVc = [[MobileInputVC alloc] init];
    mbInputVc.baseVM = [[AccountSysVM alloc] init];
    mbInputVc.type = ForRegisterType;
    [mbInputVc setAreaCode:@"86" andMobile:@""];
    
    WEAKSELF
    mbInputVc.leftNavButtonBlock = ^{
        // 点击返回
        [weakSelf go2LoginVC:nil];
    };
    
    // 重建登录页
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:mbInputVc];
    self.window.rootViewController = nav;
}


#pragma mark - 添加跳转到主页面/登录页面的通知
- (void)addAccountNotification
{
    WEAKSELF
    // 跳转到登录页面的通知
    [NotificationHelp addNotification:NotificationGo2LoginVC object:nil usingBlock:^(NSNotification *note) {
        [weakSelf go2LoginVC:note.object];
    }];
    // 跳转到主页面的通知
    [NotificationHelp addNotification:NotificationGo2MainTBC object:nil usingBlock:^(NSNotification *note) {
        [weakSelf go2MainTBC];
    }];
    // 登录成功
    [NotificationHelp addNotification:NotificationLoginSuccess object:nil usingBlock:^(NSNotification *note) {
        [weakSelf saveUserInfo:note.object];
        if (!weakSelf.wasAutoLogin) {
            [weakSelf go2MainTBC];
        }
    }];
}

#pragma mark - 保存用户信息
- (void)saveUserInfo:(NSDictionary *)data
{
    // 上传devicetoken
    [self sendDeviceToken];
    
    NSDictionary *userInfo = [data objectForKey:@"user_info"];
    UserInfoModel *userInfoModel = [UserInfoModel mj_objectWithKeyValues:userInfo];
    
    UserSaveInfo.authId = userInfoModel.sEssid?:@"";
    UserSaveInfo.userId = [NSString stringWithFormat:@"%ld", (long)userInfoModel.iUserId]?:@"";
    UserSaveInfo.mail = userInfoModel.sMail?:@"";
    UserSaveInfo.companyName = userInfoModel.sCompanyName?:@"";
    UserSaveInfo.position = userInfoModel.sPositionName?:@"";
    UserSaveInfo.name = userInfoModel.sRealName;
    UserSaveInfo.eName = userInfoModel.sEnglishName;

    if (userInfoModel.iZoneNum && 0 != userInfoModel.iZoneNum.length) {
        UserSaveInfo.areaCode = userInfoModel.iZoneNum;
    }
    if (userInfoModel.sPhone && 0 != userInfoModel.sPhone.length) {
        UserSaveInfo.mobile = userInfoModel.sPhone;
    }
    
}

#pragma mark - 发送dt(没有dt不发送，有dt发送后也不管是否成功)
- (void)sendDeviceToken
{
    NSString *deviceToken = [CommonHelper shared].deviceToken;
    if (!deviceToken || 0 == deviceToken.length) return;
    AccountSysVM *requestVM = [[AccountSysVM alloc] init];
    [requestVM sendDeviceToken:deviceToken];
}

#pragma mark - 处理UITableview会上下偏移的问题
- (void)setUPAdapteriOS11{
    if (@available(iOS 11.0, *))
    {
        [UITableView appearance].estimatedRowHeight = 0;
        [UITableView appearance].estimatedSectionFooterHeight = 0;
        [UITableView appearance].estimatedSectionHeaderHeight = 0;
        [UITableView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

@end
